package com.example.demo01.Socket.Codec.decode;

import cn.hutool.core.util.StrUtil;
import com.example.demo01.Utils.FactoryPacketInstruction;
import com.example.demo01.VO.IPacketInstruction;
import com.example.demo01.VO.TelNo01;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;


@Slf4j
@Component
public class MyMessageDecoder1 extends ByteToMessageDecoder {



    @Resource
    private   FactoryPacketInstruction factoryPacketInstruction;

    private static MyMessageDecoder1  decoder1;
    @PostConstruct
    public void init(){

        decoder1=this;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {


        log.info("MyMessageDecoder1 length:"+byteBuf.readableBytes());

        if(byteBuf.readableBytes()>=2){
           short len= byteBuf.readShort();
           log.info("MyMessageDecoder1 header length"+ len);
            IPacketInstruction packetInstruction =null;
           // 000644583030
            byteBuf.markReaderIndex();
            if(byteBuf.readableBytes()>=len-2){
                byte[] headerbt=new byte[4];
                byteBuf.readBytes(headerbt);
                String telNo=StrUtil.str(headerbt, StandardCharsets.UTF_8);
                log.info("telNo:"+telNo);
                packetInstruction= decoder1.factoryPacketInstruction.getPacketInstruction(telNo);

            }
            list.add(packetInstruction);


             //byteBuf.resetReaderIndex();

        }
        else{


            //因为前面已经读取过。
            ByteBuf frame = byteBuf.retainedDuplicate();
            //传递到下个
            list.add(frame);
        }
        //跳过读取的字节
        byteBuf.skipBytes(byteBuf.readableBytes());


    }
}
